import '../../css/reviewer/addEditItem.scss'
import React, { useEffect, useState, useRef } from 'react';
import { Button, Form, Input, Cascader, Switch, message } from 'antd';
import { departmentList } from '../../api/department/departmentList'
import { reviewerAdd, reviewerShow, reviewerEdit } from '../../api/reviewer/reviewer'
import { useNavigate, useSearchParams } from 'react-router-dom'
const ReviewerAddEdit = () => {
  // 路由跳转
  const navigate = useNavigate()
  // 路由传参
  const [paramsInfo] = useSearchParams()
  // 级联框
  const [options, setOptions] = useState()
  // 父级部门的数据展示
  const fieldName: any = { label: 'name', value: 'id', children: 'son' }
  // 调用useRef useRef 返回一个可变的 ref 对象，且只有一个current属性
  const from: any = useRef()
  //Form.useForm() 创建的 form 控制实例 
  const [form] = Form.useForm();

  // 更具id查询单条数据
  const reviewerShowInfo = async () => {
    const res: any = await reviewerShow({
      id: paramsInfo.get('id')
    })
    console.log(res);

    if (res.code === "00000") {
      // setFieldsValue方法 设置表单的值可以更改form store 中的数据
      from.current.setFieldsValue(res.data)
    }
  }

  // 获取部门接口
  const departmentListInfo = async () => {
    const res = await departmentList({})
    // console.log(res);
    setOptions(res.data)
  }

  // 成功
  const onFinish = (values: any) => {
    // console.log('Success:', values);
    if (paramsInfo.get('id')) {
      const InfoForm = {
        id: Number(paramsInfo.get('id')),
        formdata: {
          reviewer_name: values.reviewer_name,
          openid: values.openid,
          mobile: values.mobile,
          department: values.department.slice(-1)[0],
          job: values.job,
          is_use: values.is_use,
        }
      }
      reviewerEditInfo(InfoForm)
    } else {
      const InfoFormAdd = {
        reviewer_name: values.reviewer_name,
        openid: values.openid,
        mobile: values.mobile,
        department: values.department.slice(-1)[0],
        job: values.job,
        is_use: values.is_use,
      }
      console.log(InfoFormAdd);
      reviewerAddInfo(InfoFormAdd)
    }
  };

  // 添加接口
  const reviewerAddInfo = async (InfoFormAdd: any) => {
    const res: any = await reviewerAdd(InfoFormAdd)
    console.log(res);
    if (res.code === '00000') {
      message.success('添加成功');
      navigate('/index/reviewerList')
    } else {
      message.error(res.msg);
    }
  }

  // 修改接口
  const reviewerEditInfo = async (InfoForm: any) => {
    const res: any = await reviewerEdit(InfoForm)
    console.log(res);
    if (res.code === '00000') {
      message.success('修改成功');
      navigate('/index/reviewerList')
    } else {
      message.error(res.msg);
    }
  }

  // 失败
  const onFinishFailed = (errorInfo: any) => {
    console.log('Failed:', errorInfo);
    message.error('请填写内容');
  };

  // 级联框
  const changeOptions = (value: any) => {
    // console.log(value);
  };

  // 开关
  const changeSwitch = (checked: boolean) => {
    console.log(`switch to ${checked}`);
  };

  // 接口请求
  useEffect(() => {
    departmentListInfo()//列表
    reviewerShowInfo()//更具id查询
  }, [])
  return (<>
    <div className="AddEdit">
      {
        paramsInfo.get('id') ? <h3>修改</h3> : <h3>添加</h3>
      }
      <div className="form_input">
        <Form
          name="basic"
          labelCol={{ span: 6 }}
          wrapperCol={{ span: 16 }}
          style={{ maxWidth: 450 }}
          initialValues={{ remember: true }}
          onFinish={onFinish}
          onFinishFailed={onFinishFailed}
          autoComplete="off"
          form={form}
          ref={from}
        >
          <Form.Item
            label="审核人姓名"
            name="reviewer_name"
            rules={[{ required: true, message: '请输入审核姓名' }]}
          >
            <Input placeholder='请输入审核人姓名' />
          </Form.Item>

          <Form.Item
            label="openid"
            name="openid"
            rules={[{ required: true, message: '请输入openid不能为空' }]}
          >
            <Input placeholder='请输入openid' />
          </Form.Item>

          <Form.Item
            label="手机号"
            name="mobile"
            rules={[{ required: true, message: '手机号不能为空' }]}
          >
            <Input placeholder='请输入手机号' />
          </Form.Item>

          <Form.Item
            label="部门"
            name="department"
          >
            <Cascader fieldNames={fieldName} options={options} onChange={changeOptions} placeholder="请选择部门" />
          </Form.Item>

          <Form.Item
            label="职务"
            name="job"
            rules={[{ required: true, message: '请输入职务不能为空' }]}
          >
            <Input placeholder='请输入职务' />
          </Form.Item>

          <Form.Item
            label="是否启用"
            name="is_use"
          >
            <Switch defaultChecked onChange={changeSwitch} />
          </Form.Item>

          <Form.Item wrapperCol={{ offset: 5, span: 16 }}>
            <Button>
              取消
            </Button>
            {
              paramsInfo.get('id') ? <Button type="primary" htmlType="submit">
                修改
              </Button> :
                <Button type="primary" htmlType="submit">
                  添加
                </Button>
            }
          </Form.Item>
        </Form>
      </div>
    </div>
  </>);
}

export default ReviewerAddEdit;